#include "bs818.h"

uint8_t key_status = 0;

void touchInit(void)
{
    pinMode(DAT, INPUT);
    pinMode(CLK, OUTPUT);
}

uint16_t keyRead(void)
{
    uint8_t i = 0;
    uint16_t data = 0, t = 0;
    if(digitalRead(DAT) == 0)
    {
        for(i=0; i<16; i++)
        {
            data >>= 1;
            digitalWrite(CLK, 0);
            delayMicroseconds(40);            
            digitalWrite(CLK, 1);
            t  = digitalRead(DAT);
            if(t)
                data |= 0x8000;
            else
                data &= 0x7FFF;
            delayMicroseconds(40);
        }
        return data;
    }
    return 0;
}

void touchScan(void)
{
    uint16_t data = 0;
    data = keyRead();
    data &= 0x00FF;
    if(data == 0x00FB)
        key_status = KEY_MENU;
    else if(data == 0x00FD)
        key_status = KEY_LEFT;
    else if(data == 0x00FE)
        key_status = KEY_RIGHT;
    else if(data == 0x00FC)
        key_status = KEY_R_L;
    else if(data == 0x00FA)
        key_status = KEY_M_R;
    else if(data == 0x00F9)
        key_status = KEY_M_L;
    else
        key_status = KEY_NONE;
    // Serial.printf("KEY:%d\r\n", key_status);
}

